﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace TtfLibrary
{
    [TtfStructure]
    public class TtfNameRecord
    {
        public static int ContentLength = 6 * 2;

        public UInt16 PlatformId;
        public UInt16 EncodingId;
        public UInt16 LanguageId;
        public UInt16 NameId;
        public UInt16 Length;
        public UInt16 Offset;

        [TtfStop]
        public string Value;
    }

    public class OttName : IAfterRead, IAfterWrite
    {
        public static int ContentLength = 3 * 2;

        [TtfPart("Default")]
        public UInt16 Format;
        public UInt16 Count;
        public UInt16 StringOffset;
        [TtfPart("NameRecord")]
        public TtfNameRecord[] NameRecord;

        public void AfterRead(TtfStructureReader reader, int startOffset)
        {
            reader.Read(this, new[] { "Default" });
            this.NameRecord = new TtfNameRecord[Count];
            reader.Read(this, new[] { "NameRecord" });
            foreach (var nameRecord in this.NameRecord)
            {
                var offset = startOffset + this.StringOffset + nameRecord.Offset;
                reader.Position = (int)offset;
                nameRecord.Value = reader.ReadString(nameRecord.Length);
            }
        }

        public void AfterWrite(StructureWriter writer)
        {
            this.Count = (ushort)NameRecord.Length;
            this.StringOffset = (ushort)(ContentLength + Count * TtfNameRecord.ContentLength);
            
            var startPos = writer.Stream.Position;
            var stringStartPos = startPos + StringOffset;
            writer.Stream.Position = stringStartPos;

            foreach(var rec in NameRecord.OrderBy(nr => nr.Offset))
            {
                var recFileStartOffset = writer.Stream.Position;
                rec.Offset = (ushort)(recFileStartOffset - stringStartPos);
                writer.StartRegion();
                writer.WriteString(rec.Value);
                rec.Length = (ushort)(writer.Stream.Position - recFileStartOffset - 1);
                writer.EndRegion().Padding(4);
            }
            var endPos = writer.Stream.Position;

            writer.Stream.Position = startPos;
            writer.WriteObject(this, new[]{ "Default", "NameRecord" });

            writer.Stream.Position = endPos;
        }
    }
}
